import openpyxl
import SplitWord
import re
import time
import threading
import datetime


# 获取文本中的时间字符串
def get_ymd(str_ymd):
    pattern_ymd = re.compile(r'\d+年\d+月\d+日')  # 定义匹配模式
    list = re.findall(pattern_ymd, str_ymd)
    if list.__len__() > 0:
        return list[0]
    else:
        pattern_ym = re.compile(r'\d+年\d+月')
        list = re.findall(pattern_ym, str_ymd)
        if list.__len__() > 0:
            return list[0]
        else:
            pattern_y = re.compile(r'\d+年')
            list = re.findall(pattern_y, str_ymd)
            if list.__len__() > 0:
                return list[0]
            else:
                return ''

# 转化时间字符串为 YY-MM-dd的形式
def format_time(str_time):
    if str_time == 0:
        return ''
    my_time = ''
    if str_time.find('（'):
        my_time = str_time.split('（')[0]
    else:
        my_time = str_time
    try:
        if my_time.find('日') != -1:
            array = time.strptime(my_time, u"%Y年%m月%d日")
            new_time = time.strftime("%Y-%m-%d", array)
            return new_time
        if my_time.find('月') != -1:
            array = time.strptime(my_time, u"%Y年%m月")
            new_time = time.strftime("%Y-%m", array)
            return new_time
        if my_time.find('年') != -1:
            array = time.strptime(my_time, u"%Y年")
            new_time = time.strftime("%Y", array)
            return new_time
    except Exception as e:
        print(e)
        return ''


def deal_data(cols, ws):
    for col in cols:
        with threading.Lock():
            if col[0].value == 'location':
                try:
                    loc_name = SplitWord.get_loc_name(col[19].value)
                    loc_time = format_time(get_ymd(col[19].value))
                    ws.cell(row=col[0].row, column=15).value = loc_name
                    ws.cell(row=col[0].row, column=14).value = loc_time
                    print(threading.current_thread().name+'正在执行第'+str(col[0].row)+'行')
                except Exception as e:
                    print(e)
                    continue



starttime = datetime.datetime.now()
paths = ['文件3.xlsx','文件4.xlsx','文件5.xlsx']
wbs = []
threads = []
for path in paths:
    wb = openpyxl.load_workbook(path)
    # 获取所有工作表名
    names = wb.sheetnames
    # wb.get_sheet_by_name(name) 已经废弃,使用wb[name] 获取指定工作表
    sheet = wb[names[0]]
    cols = sheet.iter_rows()
    ws = wb.active
    for i in range(10):
        t = threading.Thread(target=deal_data, args=(cols, ws,))
        threads.append(t)
        print(t.name+'线程已启动')
        t.start()
    wbs.append(wb)

for t in threads:
    t.join()
for w in wbs:
    w.save("文件" + str(time.time()) + '.xlsx')

endtime = datetime.datetime.now()
print ((endtime - starttime).seconds)

# threads = []
# for i in range(5):
#     t = threading.Thread(target=loc_and_time_deal, args=(paths[i]))
#     threads.append(t)
#     t.start()
